<?php


namespace app\services\user;


use app\models\tech\TechnicianMoneyModel;
use app\models\user\DetailedMoneyModel;
use app\models\user\TechnicianModel;
use app\models\user\UserModel;
use app\services\BaseService;
use app\services\statistic\StatisticService;
use think\facade\Db;

//用户余额
class DetailMoneyService extends BaseService
{

    const RECHARGE = 1;
    const PAYORDER = 2;

    const WITHDRAW_REFUSE = 6;
    const ADMIN_ADD = 7;
    const WRITEOFF = 8;

    const ORDER_REFUND = 9;

    const ORDER_PAY = 101;
    const WITHDRAW = 102;
    const ADMIN_REDUCE = 103;


    private static $typeArr = [
        // 余额增加
        self::RECHARGE => '余额充值',
        self::PAYORDER => '余额支付',
        self::WRITEOFF => '核销送余额',

        self::WITHDRAW_REFUSE => '提现退回',
        self::ADMIN_ADD => '管理员增加',

        self::ORDER_REFUND => '订单退款',

        //余额减少
        self::ORDER_PAY => '订单余额支付',
        self::WITHDRAW => '提现扣款',
        self::ADMIN_REDUCE => '管理员减少',
    ];

    protected static function initModel()
    {
        return new DetailedMoneyModel();
    }

    public static function getTypeArr()
    {
        return self::$typeArr;
    }

    public static function getTypeText($key)
    {
        $arr = self::$typeArr;
        return isset($arr[$key]) ? $arr[$key] : '未知类型';
    }

    /**
     * 添加余额变更记录
     * @param $userId
     * @param $type
     * @param $amount
     * @param $relatedUid
     * @param $orderSn
     * @param $remark
     * @return bool
     * @throws \Exception
     */
    public static function create($userId, $type, $amount, $orderSn = '', $relatedUid = 0, $remark = '')
    {
        try {
            $userInfo = UserModel::find($userId);
            if (!$userInfo) {
                return true;
            }
            $before = $userInfo['money'];
            if ($type < 100) {
                $after = $before + $amount;
            } else {
                if ($before < $amount) {
                    throw new \Exception('用户余额不足');
                }
                $after = $before - $amount;
            }
            $userInfo->money = $after;
            $userInfo->save();
            return self::initModel()->save([
                'user_id' => $userId,
                'type' => $type,
                'before' => $before,
                'amount' => $amount,
                'after' => $after,
                'related_uid' => $relatedUid,
                'order_sn' => $orderSn,
                'remark' => $remark ? $remark : self::getTypeText($type),
            ]);
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}